package controllers

import (
	"fmt"

	"git.oschina.net/antlinker/antevent/server/app"
	"git.oschina.net/antlinker/antevent/server/bus"
	"github.com/dchest/captcha"
	"github.com/goadesign/goa"
)

// AuthController implements the auth resource.
type AuthController struct {
	*goa.Controller
	auth bus.Auth
}

// NewAuthController creates a auth controller.
func NewAuthController(service *goa.Service, allbus *bus.AllBus) *AuthController {
	return &AuthController{Controller: service.NewController("AuthController"), auth: allbus.Auth()}
}

// Login runs the login action.
func (c *AuthController) Login(ctx *app.LoginAuthContext) error {
	// AuthController_Login: start_implement

	if !captcha.VerifyString(ctx.Payload.CaptchaID, ctx.Payload.Captcha) {
		return ctx.Unauthorized(&app.AntAuthError{
			Msg: "验证码错误",
		})

	}
	token, err := c.auth.LoginToken(ctx.Payload.UserName, ctx.Payload.Password)
	fmt.Println("==========", token, err)
	if err != nil {
		return ctx.Unauthorized(&app.AntAuthError{
			Msg: "认证失败:" + err.Error(),
		})
	}
	// Put your logic here

	// AuthController_Login: end_implement
	res := &app.AntAuthBack{
		Token: token,
	}
	return ctx.OK(res)
}

// Refresh runs the refresh action.
func (c *AuthController) Refresh(ctx *app.RefreshAuthContext) error {
	// AuthController_Refresh: start_implement

	token, err := c.auth.RefreshToken(ctx.Payload.Token)

	if err != nil {
		return ctx.Unauthorized(&app.AntAuthError{
			Msg: "认证失败:" + err.Error(),
		})
	}
	res := &app.AntAuthBack{
		Token: token,
	}
	return ctx.OK(res)
}

// Captchaid runs the captchaid action.
func (c *AuthController) Captchaid(ctx *app.CaptchaidAuthContext) error {
	// AuthController_Captchaid: start_implement

	// Put your logic here

	// AuthController_Captchaid: end_implement
	res := &app.AntCaptchaBack{Captchaid: c.auth.GetCaptchaID()}
	return ctx.OK(res)
}

// Captcha runs the captcha action.
func (c *AuthController) Captcha(ctx *app.CaptchaAuthContext) error {
	// AuthController_Captcha: start_implement

	id := ctx.ID

	if ctx.Reload != nil && *ctx.Reload != "" {
		captcha.Reload(id)
	}

	ctx.ResponseData.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	ctx.ResponseData.Header().Set("Pragma", "no-cache")
	ctx.ResponseData.Header().Set("Expires", "0")
	ctx.ResponseData.Header().Set("Content-Type", "image/png")
	err := captcha.WriteImage(ctx.ResponseWriter, id, 120, 65)
	if err != nil {
		msg := "无效的验证码"
		return ctx.BadRequest(&app.AntError{
			Msg: &msg,
		})
	}
	return nil
}
